//
//  ServicePanelLightColorTemperature.swift
//  home
//
//  Created by Yun Zeng on 2019/10/5.
//  Copyright © 2019 Yun Zeng. All rights reserved.
//

import UIKit

class ServicePanelLightColorTemperature: ServicePanelBase {
    
    var light: ServiceLightColorTemperature
    
    init(light: ServiceLightColorTemperature) {
        self.light = light
        super.init(service: light.service)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // b亮度百分比控制
    lazy private var brightnessView: HueBrightnessView = {
        let view = HueBrightnessView(frame: .zero)
        view.translatesAutoresizingMaskIntoConstraints = false
        view.heightAnchor.constraint(equalToConstant: 343).isActive = true
        view.widthAnchor.constraint(equalToConstant: 123).isActive = true
        view.backgroundColor = UIColor.clear
        return view
    } ()
    
    // 常用色温选择框
    private lazy var favoriteRadios: FavoritesColorTemperatureView = {
        let view = FavoritesColorTemperatureView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 124))
        view.translatesAutoresizingMaskIntoConstraints = false
        
        view.heightAnchor.constraint(equalToConstant: 124).isActive = true
        view.widthAnchor.constraint(equalToConstant: 190).isActive = true
        view.backgroundColor = UIColor.clear
        return view
    } ()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor(hex: "dedede")
        
        // 亮度控制
        self.view.addSubview(brightnessView)
        brightnessView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        brightnessView.topAnchor.constraint(equalTo: self.customBar.bottomAnchor, constant: 45).isActive = true
        brightnessView.percentage = self.light.level.value?.toValueInt() ?? 0
        brightnessView.fillColor = UIColor(hex: "FED8B6")
        brightnessView.onProgress = { percentage in
            self.light.setLevel(percentage: percentage)
        }
        
        // 常用色温选择框
        self.view.addSubview(self.favoriteRadios)
        favoriteRadios.topAnchor.constraint(equalTo: brightnessView.bottomAnchor, constant: 58).isActive = true
        favoriteRadios.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
        self.updateService()
        favoriteRadios.onSelected = { temperature in
            self.light.setColorTemperature(temperature: temperature.value)
        }
    }
    
    override func updateService() {
        if self.light.onState == .off {
            brightnessView.percentage = 0
        } else {
            brightnessView.percentage = self.light.level.value?.toValueInt() ?? 0
        }
        let colorTempeterature = favoriteRadios.setTemperature(value: self.light.temperatureValue)
        brightnessView.fillColor = UIColor(hex: colorTempeterature.color)
        self.customBar.subtitle = self.light.desc
    }
}


// MARK: - 常用色温选项卡
fileprivate class FavoritesColorTemperatureView: UIView {
    
    struct ColorTemperature {
        var color: String
        var value: Int
    }
    
    fileprivate let temperatures: [ColorTemperature] = [
        ColorTemperature(color: "F1A253", value: 1000),
        ColorTemperature(color: "F4BB7C", value: 2000),
        ColorTemperature(color: "FED8B6", value: 3000),
        ColorTemperature(color: "FFFFFF", value: 4000),
        ColorTemperature(color: "ECF2FF", value: 5000),
        ColorTemperature(color: "B4CAFF", value: 6000)
    ]
    
    fileprivate var cells = [TemperatureView]()
    var onSelected: ((_ temperature: ColorTemperature) -> Void)?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        for index in 0 ..< self.temperatures.count {
            let frame = CGRect(x: 68 * (index % 3), y: Int(index / 3) * 63, width: 56, height: 56)
            let cell = TemperatureView(frame: frame, temperature: self.temperatures[index])
            self.addSubview(cell)
            self.cells.append(cell)
            cell.onForced = {
                self.onSelected?(self.temperatures[index])
                cell.forced = true
            }
        }
    }
    
    func setTemperature(value: Int) -> ColorTemperature {
        var index: Int?
        for i in 0 ..< self.temperatures.count {
            if self.temperatures[i].value == value {
                index = i
                break
            }
        }
        if index == nil {
            index = 3
        }
        for i in 0 ..< self.cells.count {
            if i == index! {
                self.cells[i].forced = true
            } else {
                self.cells[i].forced = false
            }
        }
        return self.temperatures[index!]
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    class TemperatureView: UIView {
        
        var forceView: UIView!
        var markColor: UIColor = UIColor.white
        
        init(frame: CGRect, temperature: ColorTemperature) {
            super.init(frame: frame)
            
            let colorView = UIView(frame: .zero)
            self.addSubview(colorView)
            colorView.translatesAutoresizingMaskIntoConstraints = false
            colorView.widthAnchor.constraint(equalTo: self.widthAnchor).isActive = true
            colorView.heightAnchor.constraint(equalTo: self.heightAnchor).isActive = true
            colorView.layer.cornerRadius = frame.width / 2
//            colorView.layer.borderColor = UIColor.white.cgColor
//            colorView.layer.borderWidth = 0.5
            colorView.backgroundColor = UIColor(hex: temperature.color)
            
            if temperature.value > 2000 && temperature.value < 6000 {
                self.markColor = UIColor(hex: "787878")
            } else {
                self.markColor = UIColor.white
            }
            
            let label = UILabel()
            let attributes: [NSAttributedString.Key : Any] = [
                NSAttributedString.Key.font: UIFont.systemFont(ofSize: 11, weight: UIFont.Weight.semibold),
                NSAttributedString.Key.kern: -0.5,
                NSAttributedString.Key.foregroundColor: self.markColor]
            label.attributedText = NSAttributedString(string: String(format: "%dk", temperature.value), attributes: attributes)
            self.addSubview(label)
            
            label.translatesAutoresizingMaskIntoConstraints = false
            label.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
            label.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
            label.textAlignment = .center
            label.autoresizingMask = .flexibleWidth
            
            self.forceView = UIView()
            forceView.translatesAutoresizingMaskIntoConstraints = false
            self.addSubview(forceView)
            
            forceView.backgroundColor = UIColor.clear
            forceView.widthAnchor.constraint(equalToConstant: self.frame.width - 9).isActive = true
            forceView.heightAnchor.constraint(equalToConstant: self.frame.width - 9).isActive = true
            forceView.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
            forceView.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
            forceView.layer.cornerRadius = (frame.width - 9) / 2
            forceView.layer.borderColor = self.markColor.cgColor
            forceView.layer.borderWidth = 2.5
            forceView.layer.opacity = 0
        }
        
        var onForced: (() -> Void)?
        override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
            self.onForced?()
        }

        var forced: Bool = false {
            didSet {
                if self.forced {
                    self.forceView.layer.opacity = 1
                } else {
                    self.forceView.layer.opacity = 0
                }
            }
        }
        
        required init?(coder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    }
}


